package org.nf.web.view;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzp
 * @Date 2024-05-20
 */
public class ForwardyView implements View {

    /**
     * 转发的地址
     */
    private final String url;

    private final Map<String,Object> map = new HashMap<>();

    public ForwardyView(String url) {
        this.url = url;
    }

    /**
     * 提供给用户设置请求作用域参数的方法
     * @param name
     * @param object
     */
    public void addObject(String name,Object object){
        map.put(name,object);
    }

    @Override
    public void render(ServletApi api) throws ServletException, IOException {

        HttpServletRequest request = api.request();
        HttpServletResponse response = api.response();
        //将map集合的数据保存到请求作用域
        map.forEach(request::setAttribute);
        //执行转发
        request.getRequestDispatcher(url).forward(request,response);

    }
}
